package org.steven.crm.core.service.authcode;

import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.BaseService;
import com.steven.common.utils.DateTimeUtil;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import com.steven.xdb.session.DBSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/10 17:55
 * @Version 1.0
 */
public class AuthCodeService extends BaseService {
    @Override
    protected String getTable() {
        return "authCode";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return null;
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    public void create(String userName, String code, String expiredTime) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("userName", userName);
        Map<String, String> data = DBManager.queryOne(getSession(), getTable(), k);
        if (data.isEmpty()) {
            k.put("code", code);
            k.put("expiredTime", expiredTime);
            this.create(k);
        } else {
            k = new HashMap<>();
            k.put("code", code);
            k.put("expiredTime", expiredTime);
            k.put("errorCount", "0");
            this.update(data.get("id"), k);
        }
    }

    public void validate(String userName, String code) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("userName", userName);
        Map<String, String> data = DBManager.queryOne(getSession(), getTable(), k);
        if (data.isEmpty()) {
            throw new ServiceException("验证码错误");
        }

        if (Integer.parseInt(data.get("errorCount")) >= 3) {
            throw new ServiceException("尝试次数过多，请重新获取验证码");
        }

        if (DateTimeUtil.getCurrentDateTime().compareTo(data.get("expiredTime")) > 0) {
            throw new ServiceException("验证码已过期，请重新获取验证码");
        }

        if (!data.get("code").equals(code)) {
            incrErrorCount(data.get("id"));
            throw new ServiceException("验证码错误");
        }
    }

    private void incrErrorCount(String id) throws Exception {
        String sql = "update " + getTable() + " set errorCount = errorCount + ? where id = ?";
        List<String> p = new ArrayList<>();
        p.add("1");
        p.add(id);
        DBManager.update(getSession(), sql, p);
        DBSession.commit(getSession());
    }


}
